package com.github.hgkmail.hello.interceptor;

import com.github.hgkmail.hello.constant.CommonResponse;
import com.github.hgkmail.hello.exception.CommonException;
import com.github.hgkmail.hello.vo.BaseVo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;

import static com.github.hgkmail.hello.constant.CommonResponse.*;

/**
 * 一些全局处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    //全局异常处理
    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public BaseVo commonException(CommonException e) {
        return new BaseVo(CODE_FAIL, "common exception", e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public BaseVo bindException(BindException e) {
        return new BaseVo(CODE_FAIL, "bind exception", e.getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public BaseVo constraintViolationException(ConstraintViolationException e) {
        return new BaseVo(CODE_FAIL, "constraint violation exception", e.getMessage());
    }

    @ExceptionHandler(AuthorizationException.class)  //权限不足
    @ResponseBody
    public BaseVo authorizationException(AuthorizationException e) {
        return new BaseVo(CODE_FAIL, "author exception", e.getMessage());
    }

    @ExceptionHandler(AuthenticationException.class)  //没有登录
    @ResponseBody
    public BaseVo authenticationException(AuthenticationException e) {
        return new BaseVo(CODE_FAIL, "auth exception", e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseVo exception(Exception e) {
        return new BaseVo(CODE_FAIL, "exception", e.getMessage());
    }

}
